use reqwest::Client;
use serde::{Deserialize, Serialize};
use std::env;

// API 请求数据结构
#[derive(Serialize)]
struct ApiRequest {
    model: String,
    stream: bool,
    messages: Vec<Message>,
}

#[derive(Serialize)]
struct Message {
    role: String,
    content: String,
}

// API 响应数据结构
#[derive(Deserialize)]
struct ApiResponse {
    choices: Vec<Choice>,
}

#[derive(Deserialize)]
struct Choice {
    message: MessageResponse,
}

#[derive(Deserialize)]
struct MessageResponse {
    content: String,
}

// 调用 API 并返回结果
async fn call_api(question: &str) -> Result<String, Box<dyn std::error::Error>> {
    let client = Client::new();
    let api_url = "http://api.tecorigin.com/v1/chat/completions";
    let api_key = "YOUR TOKEN";
    let model = "deepseek-ai/DeepSeek-R1-Distill-Qwen-32B";

    let request = ApiRequest {
        model: model.to_string(),
        stream: false,
        messages: vec![Message {
            role: "user".to_string(),
            content: question.to_string(),
        }],
    };

    let response = client
        .post(api_url)
        .header("Authorization", api_key)
        .header("Content-Type", "application/json")
        .json(&request)
        .send()
        .await?;

    if response.status().is_success() {
        let api_response: ApiResponse = response.json().await?;
        if let Some(choice) = api_response.choices.get(0) {
            Ok(choice.message.content.clone())
        } else {
            Err("No response from API".into())
        }
    } else {
        Err(format!("API request failed with status: {}", response.status()).into())
    }
}

#[tokio::main]
async fn main() {
    // 获取用户输入
    let args: Vec<String> = env::args().collect();
    if args.len() < 2 {
        eprintln!("Usage: ask <question>");
        return;
    }

    let question = &args[1..].join(" ");

    // 调用 API 并输出结果
    match call_api(question).await {
        Ok(answer) => println!("{}", answer),
        Err(e) => eprintln!("Error: {}", e),
    }
}
